﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Configuration;
using Microsoft.Reporting.WinForms;

namespace TMS
{
    public partial class StocktakingProdutsControl : UserControl
    {
        Categories cat = new Categories();
        DataSet table = new DataSet();
        Product prod = new Product();
        Int32 ProductCounter = 0;
        Stocktaking NewStocktaking = new Stocktaking();       
        Users ActiveUser = Program.GetActiveUser;
        bool edit = false;
        bool init = false;
        bool print = false;
        DateTime Today = DateTime.Today;
        string Responsible;
        string Description;

        public StocktakingProdutsControl()
        {
            InitializeComponent();
        }

        public StocktakingProdutsControl(DataGridViewRow row)
        {
            edit = true;
            
           
            InitializeComponent();
            dgvProductsList.ColumnCount = 8;
            dgvProductsList.Columns[0].HeaderText = "Бр.";
            dgvProductsList.Columns[1].HeaderText = "Бр.на Пр.";
            dgvProductsList.Columns[2].HeaderText = "Име";
            dgvProductsList.Columns[3].HeaderText = "Опис";
            dgvProductsList.Columns[4].HeaderText = "Ед.М.";
            dgvProductsList.Columns[5].HeaderText = "Количина";
            dgvProductsList.Columns[6].Visible = false;
            dgvProductsList.Columns[7].HeaderText = "Магацин";
            dgvProductsList.Columns[0].Width = 30;
            dgvProductsList.Columns[1].Width = 80;
            dgvProductsList.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            

            //if (row.Cells.Count == 2)
            //{
                NewStocktaking.ID = Convert.ToInt32(row.Cells[1].Value.ToString());
                NewStocktaking.StocktakingListID = Convert.ToInt32(row.Cells[0].Value.ToString());
                NewStocktaking.Date = Convert.ToDateTime(row.Cells[2].Value);
                Responsible = row.Cells[4].Value.ToString();
            //}
            //else
            //{
                Description = row.Cells[3].Value.ToString();
                Program.GetMainForm.Text = "Пописна листа: " + row.Cells[3].Value.ToString() + "од попис " + row.Cells[2].Value.ToString();
                cmbWarehouses.ValueMember = "name";
                FillWharehouses();
                FillStocktakingList(NewStocktaking.StocktakingListID);

                if (!NewStocktaking.GetStatus())
                {
                    btnAdd.Visible = false;
                    btnEditRemove.Visible = false;
                    grbAddProduct.Visible = false;
                }
            //}
        }

        private void StocktakingProdutsControl_Load(object sender, EventArgs e)
        {
            cmbCategory1.DisplayMember = "name";
            cmbCategory1.ValueMember = "id";
            cmbCategory2.DisplayMember = "name";
            cmbCategory2.ValueMember = "id";
            cmbCategory3.DisplayMember = "name";
            cmbCategory3.ValueMember = "id";
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            object[] product = new object[8];
            ProductCounter = dgvProductsList.Rows.Count + 1;

            Int64 quantity = Convert.ToInt64(txtQuantity.Text);
            DataSet table = new DataSet();
            table = prod.GetProductFromDBAsDataSet(Convert.ToInt32(cmbProductList.SelectedValue));
            product[0] = ProductCounter;
            product[1] = table.Tables[0].Rows[0].ItemArray[5];
            product[2] = table.Tables[0].Rows[0].ItemArray[4].ToString();
            product[3] = table.Tables[0].Rows[0].ItemArray[10];
            product[4] = table.Tables[0].Rows[0].ItemArray[11];
            product[5] = quantity;
            product[6] = table.Tables[0].Rows[0].ItemArray[0];
            product[7] = cmbWarehouses.SelectedValue.ToString();



            if (dgvProductsList.SelectedRows.Count == 0)
                dgvProductsList.Rows.Add(product);
            else
                dgvProductsList.Rows.Insert(dgvProductsList.SelectedRows[0].Index, product);

            Int32 i = 1;
            foreach (DataGridViewRow row in dgvProductsList.Rows)
            {
                row.Cells[0].Value = i;
                i++;
            }
        }

        private void cmbCategory1_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cmbCategory1.Items.Count == 0) cmbCategory1.DataSource = cat.GetAllCategory1().Tables[0];
            else
            {
                if (cmbCategory1.SelectedValue.ToString() == "1")
                {
                    cmbCategory2.DataSource = cat.GetAllCategory2("").Tables[0];
                    cmbCategory3.DataSource = cat.GetAllCategory3("", "").Tables[0];
                }
                else 
                {
                    cmbCategory2.DataSource = cat.GetAllCategory2(cmbCategory1.SelectedValue.ToString()).Tables[0];
                    cmbCategory3.DataSource = cat.GetAllCategory3(cmbCategory1.SelectedValue.ToString(), "").Tables[0];
                }
            }
            cmbProductList.DisplayMember = "Name";
            cmbProductList.ValueMember = "ID";
        }

        private void cmbCategory2_SelectedValueChanged(object sender, EventArgs e)
        {

            if (cmbCategory2.Items.Count == 0) cmbCategory2.DataSource = cat.GetAllCategory2("").Tables[0];
            else
            {
                if (cmbCategory2.SelectedValue.ToString() == "1")
                {
                    cmbCategory3.DataSource = cat.GetAllCategory3("", "").Tables[0];
                }
                else
                {
                    cmbCategory3.DataSource = cat.GetAllCategory3("", cmbCategory2.SelectedValue.ToString()).Tables[0];
                }
            }

        }

        private void cmbCategory3_SelectedValueChanged(object sender, EventArgs e)
        {
            
            if (cmbCategory3.Items.Count == 0) cmbCategory3.DataSource = cat.GetAllCategory3("", "").Tables[0];
            if (cmbCategory2.SelectedValue.ToString()!="System.Data.DataRowView")
                if (cmbCategory3.SelectedValue.ToString() != "System.Data.DataRowView")
                {

                    table = prod.GetProductFromDB(cmbCategory1.SelectedValue.ToString(), cmbCategory2.SelectedValue.ToString(), cmbCategory3.SelectedValue.ToString());
                    cmbProductList.Text = "";
                    cmbProductList.DataSource = table.Tables[0];
                    cmbProductList.Update();
                }
        }

        private void btnEditRemove_Click(object sender, EventArgs e)
        {

            if (dgvProductsList.SelectedRows.Count != 0)
            {
                cmbProductList.SelectedValue = dgvProductsList.SelectedRows[0].Cells[6].Value;
                txtQuantity.Text = dgvProductsList.SelectedRows[0].Cells[5].Value.ToString();
                cmbWarehouses.SelectedValue = dgvProductsList.SelectedRows[0].Cells[7].Value.ToString();
                foreach (DataGridViewRow row in dgvProductsList.SelectedRows)
                {
                    dgvProductsList.Rows.Remove(row);
                }
                Int32 i = 1;
                foreach (DataGridViewRow row in dgvProductsList.Rows)
                {
                    row.Cells[0].Value = i;
                    i++;
                }
            }
        }

        public void FillStocktakingList(Int32 ID)
        {
            DataSet table = new DataSet();
            MySqlDataAdapter MyDA = new MySqlDataAdapter();
            string connString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;


            MySqlConnection mysqlCon = new MySqlConnection(connString);
            mysqlCon.Open();


            string sqlSelectAll = "SELECT * from stocktaking_products WHERE Stocktaking_list_ID='"+ID+"'";
            MyDA.SelectCommand = new MySqlCommand(sqlSelectAll, mysqlCon);
            MyDA.Fill(table);
           

            foreach (DataRow row in table.Tables[0].Rows)
            {
                DataSet prod1 = prod.GetProductFromDBAsDataSet(Convert.ToInt32(row.ItemArray[1]));
                //MessageBox.Show(prod1.Tables[0].Rows[0].ItemArray[0].ToString());
                object[] product = new object[8];
                //ProductCounter = dgvProductsList.Rows.Count + 1;
                product[0] = row.ItemArray[4];
               // product[1] = prod.GetProductFromDBAsDataSet(Convert.ToInt32(row.ItemArray[2])).Tables[0].Rows[0].ItemArray[5];
               // product[2] = prod.GetProductFromDBAsDataSet(Convert.ToInt32(row.ItemArray[2])).Tables[0].Rows[0].ItemArray[4];
                product[1] = prod1.Tables[0].Rows[0].ItemArray[5];
                product[2] = prod1.Tables[0].Rows[0].ItemArray[4];
                product[3] = prod1.Tables[0].Rows[0].ItemArray[10];
                product[4] = prod1.Tables[0].Rows[0].ItemArray[11];
                product[5] = row.ItemArray[2];
               product[6] = row.ItemArray[1];
                product[7]=row.ItemArray[5];
                dgvProductsList.Rows.Add(product);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            NewStocktaking.DeleteAllStocktakigProductsForStotakingList();
            string connString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;

            MySqlConnection mysqlCon = new MySqlConnection(connString);

            mysqlCon.Open();

            foreach (DataGridViewRow row in dgvProductsList.Rows)
            {
                
                string sqlInsertProduct = "INSERT INTO stocktaking_products VALUES (DEFAULT,'" +
                                            Convert.ToInt32(row.Cells[6].Value) + "','" +
                                            Convert.ToInt32(row.Cells[5].Value) + "','" +
                                            NewStocktaking.StocktakingListID + "','" +
                                            Convert.ToInt32(row.Cells[0].Value) + "','"+
                                            row.Cells[7].Value.ToString()+"','"+
                                            NewStocktaking.ID+"')";
                MySqlCommand cmd = new MySqlCommand(sqlInsertProduct, mysqlCon);
                cmd.ExecuteNonQuery();

            }
            mysqlCon.Close();
            this.Dispose();
            Program.GetMainForm.ShowControl(ControlsEnum.WAREHOUSE_CONTROL);
        }

        public void FillWharehouses()
        {
            MySqlDataAdapter MyDA = new MySqlDataAdapter();
            DataSet table = new DataSet();
            string connString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
            MySqlConnection mysqlCon = new MySqlConnection(connString);
            mysqlCon.Open();
            string sqlSelectAll = "SELECT * from warehouses";
            MyDA.SelectCommand = new MySqlCommand(sqlSelectAll, mysqlCon);
            MyDA.Fill(table);
            mysqlCon.Close();
            table.Tables[0].Rows[0].Delete();
            cmbWarehouses.DataSource = table.Tables[0];
           

        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (print)
            {
                dgvProductsList.Visible = true;
                grbAddProduct.Visible = true;
                btnAdd.Visible = true;
                btnEditRemove.Visible = true;
                print = false;
                rpvStocktakingReport.Visible = false;
            }
            else
            {
                dgvProductsList.Visible = false;
                grbAddProduct.Visible = false;
                btnAdd.Visible =false;
                btnEditRemove.Visible = false;
                print = true;
                rpvStocktakingReport.Visible = true;

                StocktakingListData ds = new StocktakingListData();
                foreach (DataGridViewRow row in dgvProductsList.Rows)
                {
                    ds.Tables[0].Rows.Add(new object[] { row.Cells[0].Value.ToString(), row.Cells[1].Value.ToString(), row.Cells[2].Value.ToString(), row.Cells[3].Value.ToString(), row.Cells[5].Value.ToString(), row.Cells[7].Value.ToString() });
                }

                ReportParameter StocktakingDate = new ReportParameter("StocktakingDate", NewStocktaking.Date.ToString("dd-MM-yyyy"));
                ReportParameter ActiveUserPar = new ReportParameter("ActiveUser", Responsible);
                ReportParameter date = new ReportParameter("Date", Today.ToString("dd-MM-yyyy"));
                ReportParameter description = new ReportParameter("StocktakingListDescription",Description);

                ReportDataSource rds = new ReportDataSource("DS1", ds.Tables[0]);
                this.rpvStocktakingReport.LocalReport.DataSources.Add(rds);
                this.rpvStocktakingReport.LocalReport.SetParameters(StocktakingDate);
                this.rpvStocktakingReport.LocalReport.SetParameters(ActiveUserPar);
                this.rpvStocktakingReport.LocalReport.SetParameters(date);
                this.rpvStocktakingReport.LocalReport.SetParameters(description);
                this.rpvStocktakingReport.RefreshReport();
                
            }
        }


        private void ToStBack_Click(object sender, EventArgs e)
        {
            if (Program.GetMainForm.Back())
                this.Dispose();
        }


        private void ToStForward_Click(object sender, EventArgs e)
        {
            if (Program.GetMainForm.Forward())
                this.Dispose();
        }
    }
}
